package com.lgb.utils;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;

import org.springframework.web.multipart.MultipartFile;

public class FileUtils {

    /**
     * 在basePath下保存上传的文件夹
     * @param basePath
     * @param files
     */
    public static void saveMultiFile(String basePath, MultipartFile[] files) {
        if (files == null || files.length == 0) {
            return;
        }
        if (basePath.endsWith("/")) {
            basePath = basePath.substring(0, basePath.length() - 1);
        }
        for (MultipartFile file : files) {
            String filePath = basePath + "/" + file.getOriginalFilename();
            makeDir(filePath);
            File dest = new File(filePath);
            try {
                file.transferTo(dest);
            } catch (IllegalStateException | IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 确保目录存在，不存在则创建
     * @param filePath
     */
    private static void makeDir(String filePath) {
        if (filePath.lastIndexOf('/') > 0) {
            String dirPath = filePath.substring(0, filePath.lastIndexOf('/'));
            File dir = new File(dirPath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
        }
    }


    //寻找files的统计目录
    public static String findCommonDirectory(MultipartFile[] files) {
        if (files == null || files.length == 0) {
            return null;
        }

        String[] directories = new String[files.length];

        for (int i = 0; i < files.length; i++) {
            MultipartFile file = files[i];
            String filePath = file.getOriginalFilename();
            String[] pathComponents = filePath.split("/");
            if (pathComponents.length == 0) {
                return null; // 文件路径不合法
            }
            directories[i] = String.join("/", Arrays.copyOf(pathComponents, pathComponents.length - 1));
        }

        for (String directory : directories) {
            if (!directory.equals(directories[0])) {
                return null; // 文件路径没有共同目录
            }
        }

        return directories[0];
    }

    //根据绝对路径生成相对路径
    public static String generateRelativePath(String absolutePath, String basePath) {
        Path absolute = Paths.get(absolutePath);
        Path base = Paths.get(basePath);

        Path relative = base.relativize(absolute);
        return relative.toString();
    }

    //根据路径删除文件夹
    public static void deleteFolder(String folderPath) {
        File folder = new File(folderPath);

        if (!folder.exists()) {
            System.out.println("文件夹不存在：" + folderPath);
            return;
        }

        File[] files = folder.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    // 递归删除子文件夹
                    deleteFolder(file.getAbsolutePath());
                } else {
                    // 删除文件
                    file.delete();
                }
            }
        }

        // 删除空文件夹
        folder.delete();
        System.out.println("文件夹已删除：" + folderPath);
    }
}